<?php
namespace App\Logics;

use App\Models\ChannelModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\CategoryModel;

//逻辑处理
class CategoryLogic extends BaseLogic {


    public function __construct()
    {
        parent::__construct();

    }

    public  function index(array $para){
        $cha_id = isset($para['cha_id'])? $para['cha_id']:0;

        $where = $searchWhere[] = ['cha_id',0];

        $list=CategoryModel::where($searchWhere)->get();
        $list=ob_to_array($list);

        $url=config('sys.img_url').'/';
        $pid_ar=array_unique(array_column($list,'pid'));
        foreach($list as $k=>$v){
            $list[$k]['cate_pic']=$v['cate_pic']?$url.$v['cate_pic']:$v['cate_pic'];
            if(in_array($v['cate_id'],$pid_ar)){
                $list[$k]['is_son']=0;
            }else{
                $list[$k]['is_son']=1;
            }
        }
        $list=$this->tree($list);
        $channel = ChannelModel::pluck('cha_describe', 'cha_id');
        $lists=[];
        foreach($list as $k=>$v){
            $list[$k]['cha_name']=isset($channel[$v['cha_id']])?$channel[$v['cha_id']]:($v['cha_id']==0?'平台':'未知渠道');
            if($v['pid']==0){
                $lists[]=$list[$k];
            }
        }

       return  [
           'list'=>$lists,
           'channel'=>$channel,
           'where'=>$where
       ];
    }

    public  function add(array $para,Request $request){
        $cha_id= isset($para['cha_id'])?$para['cha_id']:0;
        $cate_name=isset($para['cate_name'])?$para['cate_name']:'';
        $cate_note=isset($para['cate_note'])?$para['cate_note']:'';
        $cate_code=isset($para['cate_code'])?$para['cate_code']:'';
        $cate_code_name=isset($para['cate_code_name'])?$para['cate_code_name']:'';
        $cate_hot_search=isset($para['cate_hot_search'])?$para['cate_hot_search']:'';
        $pid=isset($para['pid'])?$para['pid']:0;

        if($cha_id>0){
            $res=ChannelModel::where('cha_id',$cha_id)->count();
            if(empty($res)) return error('选择的渠道不存在');
        }
        if($pid>0 ){
            $res=CategoryModel::where('cate_id',$pid)->first();
            $res=ob_to_array($res);
            if(empty($res)) return error('该上级分类不存在');
            if($res['cha_id'] !=$cha_id) return error('上级分类与渠道不对应');
        }
        if(empty($cate_name)){
            return error('请填写分类名称');
        }
        if(empty($cate_code)){
            return error('请填写类目码');
        }
        if(empty($cate_code_name)){
            return error('请填写类目码名称');
        }
        $cate_pic='';
        if($request->hasFile('img')){
            $data=$this->uploadImg($request,'img','category');
            if($data['status']==0) return error($data['data']);
            $cate_pic=$data['data'];
        }
        $data=[
            'cha_id'=>$cha_id,
            'cate_name'=>$cate_name,
            'cate_code'=>$cate_code,
            'cate_code_name'=>$cate_code_name,
            'cate_pic'=>$cate_pic,
            'cate_hot_search'=>$cate_hot_search,
            'cate_note'=>$cate_note,
            'pid'=>$pid
        ];
        $res=CategoryModel::insert($data);
        if($res){
            return success('添加成功');
        }
        if($data['cate_pic']) $this->deleteImg($data['cate_pic']);
        return error('添加失败');
    }

    public  function edit(array $para,Request $request){
        $cate_name=isset($para['cate_name'])?$para['cate_name']:'';
        $cate_note=isset($para['cate_note'])?$para['cate_note']:'';
        $cate_code=isset($para['cate_code'])?$para['cate_code']:'';
        $cate_code_name=isset($para['cate_code_name'])?$para['cate_code_name']:'';
        $cate_hot_search=isset($para['cate_hot_search'])?$para['cate_hot_search']:'';
        $pid=isset($para['pid'])?$para['pid']:0;
        $cate_id=isset($para['cate_id'])?$para['cate_id']:0;
        $p_sort=isset($para['p_sort'])?$para['p_sort']:10;
        $is_del=isset($para['is_del'])?$para['is_del']:0;
        $is_hidden=isset($para['is_hidden'])?$para['is_hidden']:0;

        $cate= CategoryModel::where('cate_id',$cate_id)->first();
        if(empty($cate)) return error('参数有误');
        $cate=ob_to_array($cate);
        $cha_id=$cate['cha_id'];
        if($cha_id>0){
            $num=ChannelModel::where('cha_id',$cha_id)->count();
            if($num==0) return error('分类的渠道不存在');
        }
        if($pid>0){
            $res= CategoryModel::where('cate_id',$pid)->first();
            $res=ob_to_array($res);
            if(empty($res)) return error('该上级分类不存在');
            if($res['cha_id'] !=$cha_id) return error('上级分类与渠道不对应');
            $childCate=CategoryLogic::getAllChild($cha_id,$cate_id);
            if(in_array($pid,$childCate)) return error('上级分类不能是自己或自己的子类');
        }
        if(empty($cate_name)){
            return error('请填写分类名称');
        }
        if(empty($cate_code)){
            return error('请填写类目码');
        }
        if(empty($cate_code_name)){
            return error('请填写类目码名称');
        }
        $cate_pic='';
        if($request->hasFile('img')){
            $data=$this->uploadImg($request,'img','category');
            if($data['status']==0) return error($data['data']);
            $cate_pic=$data['data'];
        }
        $is_del=$is_del==1?1:0;
        $is_hidden=$is_hidden==1?1:2;
        $data=[
            'cate_name'=>$cate_name,
            'cate_code'=>$cate_code,
            'cate_code_name'=>$cate_code_name,
            'cate_hot_search'=>$cate_hot_search,
            'cate_note'=>$cate_note,
            'pid'=>$pid,
            'p_sort'=>$p_sort,
            'is_del'=>$is_del,
            'is_hidden'=>$is_hidden
        ];
        if($cate_pic) $data['cate_pic']=$cate_pic;
        $res= CategoryModel::where('cate_id',$cate_id)->update($data);
        if($res){
            if($cate_pic && $cate['cate_pic']) $this->deleteImg($cate['cate_pic']);
            return success('编辑成功');
        }
        if($cate_pic) $this->deleteImg($cate_pic);
        return error('编辑失败');
    }

    public function getEdit(int $id){
        $data= CategoryModel::where('cate_id',$id)->first();
        $data=ob_to_array($data);
        $cha_id=(int)$data['cha_id'];
        $cha_name='平台';
        if($cha_id>0){
            $channel= ChannelModel::select("cha_id")->where('cha_id',$cha_id)->first();
            if(empty($channel)) return '渠道不存在';
            $channel=ob_to_array($channel);
            $cha_name=$channel['cha_describe'];
        }

        $list= CategoryModel::where('cha_id',$cha_id)->get();
        $list=ob_to_array($list);
        $pid_ar=array_unique(array_column($list,'pid'));
        foreach($list as $k=>$v){
            if(in_array($v['cate_id'],$pid_ar)){
                $list[$k]['is_son']=0;
            }else{
                $list[$k]['is_son']=1;
            }
        }
        $list=$this->tree($list);

        $url=config('sys.img_url').'/';
        $data['cate_pic']=$data['cate_pic']?$url.$data['cate_pic']:$data['cate_pic'];
        return [
            'data'=>$data,
            'list'=>$list,
            'cha_name'=>$cha_name
        ];
    }

    /**
     *  根据渠道id获取分类
     * @param int $cha_id
     * @return array
     */
    public function getCategoryByChaId(int $cha_id){
        $data= CategoryModel::where('cha_id',$cha_id)->get();
        $data=ob_to_array($data);
        if(empty($data)){
            return [];
        }
        $pid_ar=array_unique(array_column($data,'pid'));
        foreach($data as $k=>$v){
            if(in_array($v['cate_id'],$pid_ar)){
                $data[$k]['is_son']=0;
            }else{
                $data[$k]['is_son']=1;
            }
        }
        $data=$this->tree($data);
        return $data;
    }

    /**
     * @param int $cha_id
     * @return array
     */
    public   function getCategoryHtml(int $cha_id){
        if($cha_id>0){
            $res= ChannelModel::select("cha_id")->where([['cha_status',2],['cha_id',$cha_id]])->first();
            if(empty($res)) return error('渠道不合法');
        }

        $data= CategoryModel::where('cha_id',$cha_id)->get();
        $data=ob_to_array($data);

        $pid_ar=array_unique(array_column($data,'pid'));
        foreach($data as $k=>$v){
            if(in_array($v['cate_id'],$pid_ar)){
                $data[$k]['is_son']=0;
            }else{
                $data[$k]['is_son']=1;
            }
        }

        $data=$this->tree($data);
        $html="<option value='0'>顶级分类</option>";
        foreach($data as $k=>$v){
            if($v['is_son']==0){
                $html.='<option value="'.$v['cate_id'].'"   >'.$v['level_str'].$v['cate_name'].'</option>';
            }else{
                $html.='<option value="'.$v['cate_id'].'"   >'.$v['level_str'].$v['cate_name'].'</option>';
            }
        }
        return success('ok',['html'=>$html]);
    }


    /**
     * @param int $cate_id
     * @return array
     */
    public function delImg(int $cate_id){
        $cate=CategoryModel::where('cate_id',$cate_id)->first();
        if(empty($cate)) return error('参数错误');
        $cate=ob_to_array($cate);
        CategoryModel::where('cate_id',$cate_id)->update(['cate_pic'=>'']);
        if($cate['cate_pic']) $this->deleteImg($cate['cate_pic']);
        return success('删除成功');
    }


    /** 根据cha_id获取
     * @param int $cha_id
     * @param array $fields
     * @return mixed
     */
    public static function getListByChaId(int $cha_id,$fields=['cate_id','cate_name','pid']){
        $where=[
            ['is_del',0],
            ['is_hidden',2],
        ];
        $data= CategoryModel::where('cha_id',$cha_id)->where($where)->select($fields)->get();
        return ob_to_array($data);
    }
    public static function getCategory($fields=['cate_id','cate_name','pid']){

        $where=[
            ['is_del',0],
            ['is_hidden',2],
        ];
       $data= CategoryModel::where($where)->select($fields)->get();
       return ob_to_array($data);
    }

    //判断该数据是否存在
    public static function isOne($id){
        $id=(int)$id;
        $where=[
            ['is_del',0],
            ['is_hidden',2],
            ['cate_id',$id]
        ];
        return CategoryModel::where($where)->count();
    }

    //获取一条数据
    public static function getOne($id,$fields=['*']){
        $id=(int)$id;
        $where=[
            ['is_del',0],
            ['is_hidden',2],
            ['cate_id',$id]
        ];
        $data= CategoryModel::where($where)->select($fields)->first();
        return ob_to_array($data);
    }

    //获取所有子集
    public static function getAllChild($cha_id,$pid){
        $cha_id=(int)$cha_id;
        $pid=(int)$pid;
        $cate=CategoryModel::where('cha_id',$cha_id)->pluck('pid','cate_id');
        if(empty($cate)) return [];
        $ar=[$pid];
        while(true){
            $n=count($ar);
            foreach($cate as $k=>$v){
                if(in_array($v,$ar)){
                    $ar[]=$k;
                    unset($cate[$k]);
                }
            }
            if($n==count($ar))break;
        }
        return $ar;
    }

    public function  getCategoryLevel(int $id){
        static $level=0;
        $cate=CategoryModel::where('cate_id',$id)->select('pid')->first();
        if($cate){
            $cate=ob_to_array($cate);
            if($cate['pid']>0){
                $level+=1;
                $this->getCategoryLevel($cate['pid']);
            }
        }
        return $level;
    }

    public function getLevelStr(int $level){
        $str="|&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        $level_str='';
        for($i=0;$i<$level;$i++){
            $level_str.=$str;
        }
        return $level_str;
    }

    public function getChildHtml(int $id){
        $cate=CategoryModel::where('cate_id',$id)->select('cha_id')->first();

        if(empty($cate)) return '';
        $cate=ob_to_array($cate);
        $cha_id=(int)$cate['cha_id'];

        $data=CategoryModel::where('pid',$id)->get();
        $data=ob_to_array($data);

        $pid_ar=CategoryModel::where('cha_id',$cha_id)->pluck('pid');
        $pid_ar=ob_to_array($pid_ar);

        if($data){
            $channel =ChannelModel::pluck('cha_describe', 'cha_id');
            $channel=ob_to_array( $channel);
            $level=$this->getCategoryLevel($data[0]['cate_id']);
            $level_str=$this->getLevelStr($level);
            $url=config('sys.img_url').'/';
            foreach($data as $k=>$v){
                $data[$k]['level']=$level;
                $data[$k]['cate_pic']=$url.$v['cate_pic'];
                $data[$k]['level_str']=$level_str;
                $data[$k]['cha_name']=isset($channel[$v['cha_id']])?$channel[$v['cha_id']]:($v['cha_id']==0?'平台':'未知渠道');
                if(in_array($v['cate_id'],$pid_ar)){
                    $data[$k]['is_son']=0;
                }else{
                    $data[$k]['is_son']=1;
                }
            }
        }





        $html='';
        foreach($data as $v){
            $html.="<tr id='tr".$v['cate_id']."'  class='trpid".$v['pid']."'  >
                                            <td >".$v['cate_id']."  </td>
                                            <td >".$v['level_str'].$v['cate_name']." </td>
                                            <td >".$v['cate_code']."</td>";

            $html.="<td ><img width='100' src='".$v['cate_pic']."'   ></td>";
            if($v['is_del']==0){
                $html.="<td><span   style='color:blue;'>否</span></td>";
            }else{
                $html.="<td><span   style='color:red;'>是</span></td>";
            }
            if($v['is_hidden']==1){
                $html.="<td><span   style='color:blue;'>否</span></td>";
            }else{
                $html.="<td><span   style='color:red;'>是</span></td>";
            }
            $html.="<td>".$v['cha_name']."</td><td>".$v['level']."</td>";

            if($v['is_son']==0){
                $html.="<td> <span onclick='showChild(".$v['cate_id'].")' class='showChild' style='border - radius:5px;padding:5px;background:#00a7d0;color:#f9f9f9' data-id='".$v['cate_id']."' >查看子分类</span></td>";
            }else{
                $html.="<td> <span   class='showChild' style='border-radius:5px;padding:5px;background:#00a7d0;color:red;' data-id='".$v['cate_id']."' >无子类</span></td>";
            }
            $html.="<td><a href='/admin/category/edit?id=".$v['cate_id']."'>编辑</a></td>";
            $html.="</tr>";
        }

        return $html;
    }





}
